<template>
  <div class="delivery-tasks">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">待接单任务</h2>
        <p class="page-desc">请及时处理以下待接收的任务包，开始您的配送之旅</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-card class="search-card" shadow="never">
        <div class="search-form">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-input
                v-model="searchForm.packageId"
                placeholder="任务包编号"
                clearable
                prefix-icon="Search"
              />
            </el-col>
            <el-col :span="6">
              <el-input
                v-model="searchForm.deliveryArea"
                placeholder="配送区域"
                clearable
                prefix-icon="Location"
              />
            </el-col>
<!--            <el-col :span="6">-->
<!--              <el-select-->
<!--                v-model="searchForm.priority"-->
<!--                placeholder="优先级"-->
<!--                clearable-->
<!--                style="width: 100%"-->
<!--              >-->
<!--                <el-option label="普通" value="normal" />-->
<!--                <el-option label="紧急" value="urgent" />-->
<!--                <el-option label="特急" value="super_urgent" />-->
<!--              </el-select>-->
<!--            </el-col>-->
          </el-row>
          <div class="search-actions">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 任务包列表 -->
    <div class="tasks-section">
      <div class="tasks-header">
        <h3>待接单任务列表 ({{ total }})</h3>
        <div class="view-toggle">
          <el-button-group>
            <el-button 
              :type="viewMode === 'card' ? 'primary' : ''" 
              @click="viewMode = 'card'"
            >
              <el-icon><Grid /></el-icon>
              卡片视图
            </el-button>
            <el-button 
              :type="viewMode === 'table' ? 'primary' : ''" 
              @click="viewMode = 'table'"
            >
              <el-icon><List /></el-icon>
              表格视图
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 卡片视图 -->
      <div v-if="viewMode === 'card'" class="tasks-grid">
        <el-card 
          v-for="taskPackage in taskPackages" 
          :key="taskPackage.packageId"
          class="task-package-card"
          shadow="hover"
        >
          <template #header>
            <div class="package-header">
              <span class="package-id">{{ taskPackage.packageId }}</span>
              <el-tag :type="getStatusType(taskPackage.packageStatus)" size="small" effect="light">
                {{ getStatusText(taskPackage.packageStatus) }}
              </el-tag>
            </div>
          </template>
          
          <div class="package-body">
            <div class="info-item main-info">
              <el-icon><LocationInformation /></el-icon>
              <span>{{ taskPackage.deliveryArea || '目标区域未指定' }}</span>
            </div>
            
            <div class="stats-row">
              <div class="stat-item">
                <span class="stat-label">订单数</span>
                <span class="stat-value">{{ taskPackage.orderCount }} 单</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">预计距离</span>
                <span class="stat-value">{{ taskPackage.estimatedDistance }} 公里</span>
              </div>
              <div class="stat-item reward">
                <span class="stat-label">预计收益</span>
                <span class="stat-value">¥ {{ taskPackage.totalReward }}</span>
              </div>
            </div>
          </div>
          
          <div class="package-actions">
            <el-button type="primary" plain @click="handleAcceptTask(taskPackage)">
              <el-icon><Check /></el-icon>
              立即接单
            </el-button>
            <el-button type="info" plain @click="viewTaskDetail(taskPackage)">
              <el-icon><View /></el-icon>
              查看详情
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 表格视图 -->
      <div v-else class="tasks-table">
        <el-table :data="taskPackages" style="width: 100%" v-loading="loading" stripe>
            <el-table-column prop="packageId" label="任务包ID" min-width="180" />
            <el-table-column prop="deliveryArea" label="配送区域" min-width="200" />
            <el-table-column prop="orderCount" label="订单数" align="center" width="100" />
            <el-table-column prop="totalReward" label="预计收益(¥)" align="center" width="120" />
            <el-table-column prop="estimatedDistance" label="预计距离(km)" align="center" width="140" />
            <el-table-column label="操作" fixed="right" width="220" align="center">
                <template #default="{ row }">
                    <el-button type="primary" size="small" @click="handleAcceptTask(row)">接单</el-button>
                    <el-button type="info" size="small" @click="viewTaskDetail(row)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>
      </div>

       <!-- 分页 -->
      <div class="pagination-section">
         <el-pagination
          v-if="total > 0"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pagination.pageSize"
          :current-page="pagination.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 50, 100]"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Search, Grid, List, Location, Clock, View, Check, LocationInformation } from '@element-plus/icons-vue';
import { getTaskPackages, acceptTaskPackage } from '@/assets/delivery.js';

const router = useRouter();

const loading = ref(false);
const viewMode = ref('card');
const taskPackages = ref([]);
const total = ref(0);

const searchForm = reactive({
  packageId: '',
  deliveryArea: '',
  priority: '',
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
});

const fetchTaskPackages = async () => {
  loading.value = true;
  const queryParams = {
    page: pagination.currentPage,
    size: pagination.pageSize,
    status: 'pending', // **关键：硬编码状态**
    ...searchForm,
  };
  try {
    const response = await getTaskPackages(queryParams);
    if (response.data && response.data.data) {
      taskPackages.value = response.data.data.records || [];
      total.value = response.data.data.total || 0;
    } else {
      taskPackages.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取待接单任务列表失败:', error);
    ElMessage.error('获取待接单任务列表失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchTaskPackages();
});

const handleRefresh = () => {
  fetchTaskPackages();
  ElMessage.success('列表已刷新');
};

const handleSearch = () => {
  pagination.currentPage = 1;
  fetchTaskPackages();
};

const resetSearch = () => {
  Object.assign(searchForm, {
    packageId: '',
    deliveryArea: '',
    priority: '',
  });
  handleSearch();
};

const handleAcceptTask = async (taskPackage) => {
  try {
    await ElMessageBox.confirm(`确认接收任务包 ${taskPackage.packageId} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    });
    // 假设 acceptTaskPackage API 只需要 packageId
    await acceptTaskPackage(taskPackage.packageId);
    ElMessage.success('接单成功');
    handleRefresh(); // 刷新列表
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('接单失败');
    }
  }
};

const viewTaskDetail = (taskPackage) => {
  router.push(`/delivery/tasks/${taskPackage.packageId}`);
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchTaskPackages();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchTaskPackages();
};

const getStatusText = (status) => ({ 0: '待接单', 1: '配送中', 2: '已完成', 3: '已取消' }[status] || '未知');
const getStatusType = (status) => ({ 0: 'info', 1: 'warning', 2: 'success', 3: 'danger' }[status] || 'info');
const getTaskCardClass = (status) => ({ 0: 'pending' }[status] || '');

</script>

<style scoped lang="scss">
.delivery-tasks {
  padding: 24px;
  background-color: #f7f8fa;
}

.page-header {
  margin-bottom: 20px;
  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
  }
  .page-desc {
    font-size: 14px;
    color: #909399;
    margin-top: 4px;
  }
}

.search-card {
  margin-bottom: 24px;
  .search-actions {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.tasks-section {
  .tasks-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    h3 {
      font-size: 18px;
      font-weight: 600;
    }
  }
}

.tasks-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.task-package-card {
  border-radius: 10px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    transform: translateY(-5px);
  }

  .package-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    font-size: 16px;
    color: #303133;
  }
  
  .package-body {
    padding: 16px 0;
    .main-info {
      font-size: 14px;
      color: #606266;
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      gap: 6px;
    }
    .stats-row {
      display: flex;
      justify-content: space-between;
      text-align: center;
      padding: 12px;
      background-color: #fafafa;
      border-radius: 6px;
    }
    .stat-item {
      display: flex;
      flex-direction: column;
      gap: 4px;
      .stat-label {
        font-size: 12px;
        color: #909399;
      }
      .stat-value {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
      &.reward .stat-value {
        color: #f56c6c;
        font-weight: 600;
      }
    }
  }

  .package-actions {
    border-top: 1px solid #f2f6fc;
    padding-top: 16px;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    
    .el-button {
      width: 48%;
    }
  }
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style> 